//
//  ExpressDetailChangeViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/9/2.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ExpressDetailChangeViewController.h"
#import "ExpressDetail.h"
#import "SocketRequest.h"
#import "ExpressDetailChangeCell.h"
#import "Singleton.h"
#import "ComMethod.h"

@interface ExpressDetailChangeViewController ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    
    NSString *_telephone;
    NSString *_floor;
    NSString *_room;
    NSString *_address;
}

@end

@implementation ExpressDetailChangeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self rightBarButtonItemTitle:@"保存" Method:@selector(saveExpress)];
    [self setTableHeaderView];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 0.1)];
    _telephone = self.express.telephone;
    NSRange range = [self.express.address rangeOfString:@"#"];
    if (range.location == NSNotFound) {
        _room = self.express.address;
    } else {
        NSArray *array = [self.express.address componentsSeparatedByString:@"#"];
        _floor = [SocketMethod subArray:array Index:0];
        _room = [SocketMethod subArray:array Index:1];
    }
    if (self.isChangeTelephone) {
        self.title = @"修改收件人手机号";
    } else {
        self.title = @"修改楼房号";
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.tableView endEditing:YES];
}

- (void)backLastView {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setTableHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    UILabel *expressIdLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 10, 280, 20)];
    expressIdLabel.font = [UIFont systemFontOfSize:14];
    expressIdLabel.textColor = AssistTextColor;
    expressIdLabel.text = [NSString stringWithFormat:@"运单号：%@",self.express.expressId];
    [headerView addSubview:expressIdLabel];
    self.tableView.tableHeaderView = headerView;
}

- (void)saveExpress {
    [self.tableView endEditing:YES];
    if (self.isChangeTelephone) {
        if (_telephone.length <= 0) {
            [DSToast showText:@"请输入手机号" InView:self.view];
        }else if (![ComMethod judgeIsLegal:_telephone Limit:TelephoneLimit]) {
            [DSToast showText:@"请输入正确的11位手机号" InView:self.view];
        } else {
            [self saveExpressSocket];
        }
    } else {
        if (![ComMethod judgeIsLegal:_floor Limit:FloorLimit]) {
            [DSToast showText:@"请输入正确的楼号" InView:self.view];
        } else if (![ComMethod judgeIsLegal:_room Limit:FloorLimit]) {
            [DSToast showText:@"请输入正确的房号" InView:self.view];
        } else {
            [self saveExpressSocket];
        }
    }
}

- (void)saveExpressSocket {
    [ToastActivity makeActivity:@"修改运单号中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STSA"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.express.inwayExpressId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:_telephone] length:16];
    NSString *address = @"";
    if (_floor.length > 0) {
        address = [NSString stringWithFormat:@"%@#%@",[SocketMethod checkNull:_floor],[SocketMethod checkNull:_room]];
    } else {
        address = [SocketMethod checkNull:_room];
    }
    _address = address;
    [mutableData appendBytes:[SocketMethod checkLegal:address] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//获取快递详情
- (void)getExpressDetailSocket {
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STS9"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:self.express.inwayExpressId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isChangeTelephone) {
        return 1;
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"ExpressDetailChangeCell";
    ExpressDetailChangeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpressDetailChangeCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (self.isChangeTelephone) {
        cell.nameLbel.text = @"收件人:";
        cell.inputTextField.text = _telephone;
        cell.inputTextField.placeholder = @"请输入收件人手机号";
        cell.inputTextField.delegate = self;
        cell.inputTextField.returnKeyType = UIReturnKeyDone;
        [cell.inputTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        cell.inputTextField.tag = 10;
        [cell.inputTextField becomeFirstResponder];
    } else {
        if (indexPath.row == 0) {
            cell.nameLbel.text = @"楼号:";
            cell.inputTextField.text = _floor;
            cell.inputTextField.placeholder = @"请输入楼号";
            cell.inputTextField.delegate = self;
            cell.inputTextField.returnKeyType = UIReturnKeyNext;
            cell.inputTextField.tag = 11;
            [cell.inputTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
            [cell.inputTextField becomeFirstResponder];
        } else if (indexPath.row == 1) {
            cell.nameLbel.text = @"房号:";
            cell.inputTextField.text = _room;
            cell.inputTextField.placeholder = @"请输入房号";
            cell.inputTextField.delegate = self;
            cell.inputTextField.returnKeyType = UIReturnKeyDone;
            cell.inputTextField.tag = 12;
            [cell.inputTextField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
        }
    }
    return cell;
}

- (void)textFieldEditingChanged:(UITextField *)textField {
    if (textField.tag == 10) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    } else {
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
}

#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 10) {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    } else {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:FloorLimit] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if (![string isEqualToString:filtered]) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.returnKeyType == UIReturnKeyDone) {
        [textField resignFirstResponder];
    } else if (textField.returnKeyType == UIReturnKeyNext) {
        UITextField *textField = (UITextField *)[self.tableView viewWithTag:12];
        [textField becomeFirstResponder];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 10) {
        _telephone = textField.text;
    } else if (textField.tag == 11) {
        _floor = textField.text;
    } else if (textField.tag == 12) {
        _room = textField.text;
    }
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        if ([code isEqualToString:SuccessSocket]) {
            if (self.express.telephone.length <= 0) {
                [self getExpressDetailSocket];
            } else {
                self.express.telephone = _telephone;
                self.express.address = _address;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateexpresssuccess" object:nil];
                [ToastActivity makeSuccess:@"修改成功" InView:self.view];
                [self performSelector:@selector(backLastView) withObject:nil afterDelay:1];
            }
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            NSString *content = [SocketMethod stringDecryHexData:data];
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    ExpressDetail *detail = [[ExpressDetail alloc] initWithString:string];
                    self.express.telephone = detail.telephone;
                    self.express.expressType = detail.expressType;
                    self.express.position = detail.position;
                    self.express.address = detail.address;
                    self.express.smsType = detail.smsType;
                    self.express.isOverdue = detail.isOverdue;
                    self.express.remark = detail.remark;
                    self.express.receiveTime = detail.receiveTime;
                    break;
                }
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateexpresssuccess" object:nil];
            [ToastActivity makeSuccess:@"修改成功" InView:self.view];
            [self performSelector:@selector(backLastView) withObject:nil afterDelay:1];
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [ToastActivity makeError:msg InView:self.view];
}

- (void)dealloc {
    _socketRequest = nil;
    self.express = nil;
}

@end
